package com.example.qu_tao.View;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.qu_tao.R;
import com.example.qu_tao.adapter.LiaoYiLiaoAdapter;
import com.example.qu_tao.model.LiaoYiLiaoMessage;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class LiaoYiLiaoActivity extends AppCompatActivity {
    private RecyclerView chatRecyclerView;
    private EditText chatInput;
    private Button btnSend;
    private ImageButton btnBack;
    private LiaoYiLiaoAdapter liaoliliaoAdapter;
    private List<LiaoYiLiaoMessage> messageList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_liaoyiliao); // 聊天界面的布局文件
        // 初始化视图
        chatRecyclerView = findViewById(R.id.chat_recycler_view);
        chatInput = findViewById(R.id.chat_input);
        btnSend = findViewById(R.id.btn_send);
        btnBack = findViewById(R.id.btn_back);

        // 设置RecyclerView
        liaoliliaoAdapter = new LiaoYiLiaoAdapter(messageList);
        chatRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        chatRecyclerView.setAdapter(liaoliliaoAdapter);

        // 发送按钮点击事件
        btnSend.setOnClickListener(v -> {
            String messageContent = chatInput.getText().toString().trim();
            if (!TextUtils.isEmpty(messageContent)) {
                // 创建新消息
                LiaoYiLiaoMessage message = new LiaoYiLiaoMessage(
                        messageContent,
                        new Date(),
                        true // 假设是用户发送的消息
                );

                // 添加到消息列表
                messageList.add(message);
                // 通知适配器数据变化
                liaoliliaoAdapter.notifyItemInserted(messageList.size() - 1);
                // 滚动到最后一条消息
                chatRecyclerView.scrollToPosition(messageList.size() - 1);
                // 清空输入框
                chatInput.setText("");
            } else {
                Toast.makeText(this, "消息不能为空", Toast.LENGTH_SHORT).show();
            }
        });

        // 返回按钮点击事件
        btnBack.setOnClickListener(v -> {
            finish();
        });
    }
}